package com.foreveross.crawl.adapter.sub.impl20140402.v3.airfrance;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.foreveross.crawl.adapter.PlaneInfoEntityBuilder;
import com.foreveross.crawl.common.domain.BaseHBaseEntity;
import com.foreveross.crawl.domain.airfreight.TransitEntity;
import com.foreveross.crawl.domain.airfreight.doub.DoublePlaneInfoEntity;
import com.foreveross.crawl.domain.airfreight.doub.ReturnDoublePlaneInfoEntity;
import com.foreveross.crawl.domain.airfreight.doub.ReturnTransitEntity;
import com.foreveross.taskservice.common.bean.TaskModel;

/**
 * 法国航空常工具方法
 * 
 * @author fb
 */
@SuppressWarnings("deprecation")
public class AirfranceUtils2 {

	private final static Logger logger = LoggerFactory
			.getLogger(AirfranceUtils2.class);
	private static Map<List<String>, DoublePlaneInfoEntity> doublePlane = new HashMap<List<String>, DoublePlaneInfoEntity>();
	private static Map<String, ReturnDoublePlaneInfoEntity> rePlane = new HashMap<String, ReturnDoublePlaneInfoEntity>();
	private static List<String> key = new ArrayList<String>();

	/**
	 * 去程基本信息数据组装
	 * 
	 * @param bound
	 */
	@SuppressWarnings("unchecked")
	public static DoublePlaneInfoEntity flightBaseInfoAssembly(
			Map<String, Object> bounds, TaskModel taskQueue) {
		DoublePlaneInfoEntity dpie = null;
		List<Map<String, String>> transits = (List<Map<String, String>>) bounds
				.get("transits");
		Map<String, String> bound = transits.get(0);

		String company = bound.get("company");
		String cabinName = bound.get("commercialClass");
		String duration = (String) bounds.get("duration");
		String fromDate = bound.get("fromDate");
		String toDate = bound.get("toDate");
		String flightNo = bound.get("flightNo");
		String flightType = bound.get("flightType");
		String carrierKey = bound.get("flightCarrier");// af
		String price = bound.get("priceFormatted");
		String fromAirPortName = bound.get("fromAddress");
		String fromAirPort = bound.get("fromAddress");
		String toAirPortName = bound.get("toAddress");
		String toAirPort = bound.get("toAddress");
		try {
			dpie = PlaneInfoEntityBuilder.buildPlaneInfo(taskQueue, carrierKey,
					company, company, fromDate, toDate, flightNo, null, null,
					null, null, DoublePlaneInfoEntity.class);
			dpie.setCurrency("CNY");
			dpie.setFlightDuration(timeParse(duration));
			dpie.setFlightType(flightType);
			dpie.getTransits().addAll(
					transitAssembly(transits, taskQueue.getFlightDate()));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return dpie;
	}

	/**
	 * 回程基本信息数据组装
	 * 
	 * @param bound
	 */
	@SuppressWarnings("unchecked")
	public static ReturnDoublePlaneInfoEntity flightReturnBaseInfoAssembly(
			Map<String, Object> bounds, TaskModel taskQueue) {
		ReturnDoublePlaneInfoEntity rdpie = null;

		List<Map<String, String>> transits = (List<Map<String, String>>) bounds
				.get("transits");
		Map<String, String> bound = transits.get(0);
		String company = bound.get("company");
		String duration = (String) bounds.get("duration");
		String fromDate = bound.get("fromDate");
		String toDate = bound.get("toDate");
		String flightNo = bound.get("flightNo");
		String carrierKey = bound.get("flightCarrier");
		String flightType = bound.get("flightType");
		try {
			rdpie = PlaneInfoEntityBuilder.buildPlaneInfo(taskQueue,
					carrierKey, company, company, fromDate, toDate, flightNo,
					null, null, null, null, ReturnDoublePlaneInfoEntity.class);
			rdpie.setCurrency("CNY");
			rdpie.setFlightDuration(timeParse(duration));
			rdpie.setFlightType(flightType);
			rdpie.getReturnTransits().addAll(
					returnTransitAssembly(transits,
							taskQueue.getReturnGrabDate()));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return rdpie;
	}

	public static <T extends BaseHBaseEntity> List<TransitEntity> transitAssembly(
			List<Map<String, String>> transits, String currDate) {
		List<TransitEntity> tes = new ArrayList<TransitEntity>();
		TransitEntity te = null;
		TransitEntity frist = null;
		TransitEntity second = null;

		// // 航段小于2的没有中转信息
		// if (transits.size() < 2) {
		// System.out.println("transits.size()="+transits.size());
		// te = new TransitEntity();
		// te.setStartTime(PlaneInfoEntityBuilder.getFlightTime(currDate,
		// transits.get(0).get("fromDate").replaceAll("\\s", "")));
		// te.setEndTime(PlaneInfoEntityBuilder.getFlightTime(currDate,
		// transits.get(0).get("toDate").replaceAll("\\s", "")));
		// te.setCabinName(transits.get(0).get("cabinName"));
		// te.setFlightType(transits.get(0).get("flightNo"));
		// tes.add(te);
		// return tes;
		// }
		try {
			for (Map<String, String> map : transits) {
				te = PlaneInfoEntityBuilder.buildTransitEntity(
						map.get("flightNo"), null, map.get("flightCarrier"),
						map.get("company"), map.get("company"), map.get("fromAddressCode"),
						map.get("fromAddress"), map.get("toAddressCode"), map.get("toAddress"),
						null, TransitEntity.class);
				te.setStartTime(PlaneInfoEntityBuilder.getFlightTime(currDate,
						map.get("fromDate").replaceAll("\\s", "")));
				te.setEndTime(PlaneInfoEntityBuilder.getFlightTime(currDate,
						map.get("toDate").replaceAll("\\s", "")));
				te.setCabinName(map.get("cabinName"));
				te.setFlightType(map.get("flightType"));
				tes.add(te);
			}
		} catch (Exception e) {
			logger.error("中转装配异常", e);
		}

		// 计算中转时间
		for (int i = 0; i < tes.size(); i++) {
			if (i == tes.size() - 1) {
				break;
			}

			frist = tes.get(i);
			second = tes.get(i + 1);
			frist.setStayTime(second.getStartTime().getTime()
					- frist.getEndTime().getTime());
		}

		return tes;
	}

	public static List<ReturnTransitEntity> returnTransitAssembly(
			List<Map<String, String>> bounds, String currDate) {
		List<ReturnTransitEntity> tes = new ArrayList<ReturnTransitEntity>();
		ReturnTransitEntity te = null;
		ReturnTransitEntity frist = null;
		ReturnTransitEntity second = null;

		// // 航段小于2的没有中转信息
		// if (bounds.size() < 2) {
		// return tes;
		// }

		try {
			for (Map<String, String> map : bounds) {
				te = PlaneInfoEntityBuilder.buildTransitEntity(
						map.get("flightNo"), null, map.get("company"),
						map.get("company"), map.get("company"), map.get("fromAddressCode"),
						map.get("fromAddress"), map.get("toAddressCode"), map.get("toAddress"),
						null, ReturnTransitEntity.class);
				te.setStartTime(PlaneInfoEntityBuilder.getFlightTime(currDate,
						map.get("fromDate").replaceAll("\\s", "")));
				te.setEndTime(PlaneInfoEntityBuilder.getFlightTime(currDate,
						map.get("toDate").replaceAll("\\s", "")));
				te.setCabinName(map.get("cabinName"));
				te.setFlightType(map.get("flightType"));
				tes.add(te);
			}
		} catch (Exception e) {
			logger.error("中转装配异常", e);
		}

		// 计算中转时间
		for (int i = 0; i < tes.size(); i++) {
			if (i == tes.size() - 1) {
				break;
			}

			frist = tes.get(i);
			second = tes.get(i + 1);
			frist.setStayTime(second.getStartTime().getTime()
					- frist.getEndTime().getTime());
		}

		return tes;
	}

	/**
	 * 仓位数据组装
	 * 
	 * @param bounds
	 * @param cabins
	 * @param clazz
	 * @param cabinTypeLable
	 */
	public static <T extends BaseHBaseEntity> Set<T> cabinInfoAssembly(
			Map<String, Object> bounds, Set<T> cabins, Class<T> clazz,
			String cabinTypeLable) {
		List<Map<String, String>> transits = (List<Map<String, String>>) bounds
				.get("transits");
		Map<String, String> bound = transits.get(0);
		String priceOne = bound.get("priceFormatted");
		T cabin = null;
		try {
			cabin = PlaneInfoEntityBuilder.buildCabinInfo(cabinTypeLable,
					cabinTypeLable, null, priceOne, null, null, null, clazz);
			cabins.add(cabin);
		} catch (Exception e) {
			logger.error("仓位组装异常：", e);
		}
		return cabins;
	}

	/**
	 * 时间格式化
	 * 
	 * @param date
	 *            xx小时xx分钟等这样格式
	 * @return
	 */
	public static String[] timeAddressSeparator(String ta) {
		String result[] = new String[2];

		if (StringUtils.isNotBlank(ta)) {
			if (ta.contains("+")) {
				result[0] = ta.substring(0, ta.indexOf(")")).replaceAll(
						"\\s|\\(", "");
				result[1] = ta.substring(ta.indexOf(")") + 1).replaceAll(" - ",
						"");
			} else {
				result[0] = ta.substring(0, ta.indexOf(" ")).replaceAll(
						"\\s|\\(", "");
				result[1] = ta.substring(ta.indexOf(" ")).replaceAll(" - ", "");
			}

		}

		return result;
	}

	/**
	 * 时间格式化
	 * 
	 * @param date
	 *            xx小时xx分钟等这样格式
	 * @return
	 */
	public static long timeParse(String date) {
		long time = 0;
		List<Integer> dates = new ArrayList<Integer>();
		Pattern pattern = Pattern.compile("(\\d{1,})");
		Matcher matcher = pattern.matcher(date);

		while (matcher.find()) {
			dates.add(Integer.parseInt(matcher.group()));
		}

		if (dates.size() == 2) {
			time += dates.get(0) * 60 * 60 * 1000;
			time += dates.get(1) * 60 * 1000;
		} else {
			time += dates.get(0) * 60 * 1000;
		}

		return time;
	}
}
